<template>
    <div id="map-container" class="map" ref="map"></div>

</template>

<script>
// import { getBaseStations } from "@/api/home";
import "leaflet-editable";
import 'leaflet/dist/leaflet.css'
import L from 'leaflet'
const img1 = '/money.png'
export default {
    name: "",
    data() {
        return {
            map: "",
            icons: img1,
            marker: "", // 点击基站图标
            Url: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
            latLng: { lat: "34.26562", lng: "108.95351" },
            NewUrl: img1,
            editlayers: [],
            boxSelection: []
        };
    },
    computed: {
        // show() {
        //     return this.$store.state.mapShow;
        // }
    },
    mounted() {
        this.init();
    },
    beforeUnmount() {
        this.map.off();
        this.map.remove();
    },
    methods: {
        init() {
            const _this = this;
            this.map = L.map("map-container", {
                center: L.latLng(34.26562, 108.95351), // 地图中心
                zoom: 13, //缩放比列
                minZoom: 5,
                minNativeZoom: 7,
                // zoomControl: false, //禁用 + - 按钮
                doubleClickZoom: false, // 禁用双击放大
                attributionControl: false, // 移除右下角leaflet标识
                editable: true //地图编辑
            });
            // tileLayer 用于在地图上加载和显示瓦片图层。
            // {s} 是指可用的子域之一（按顺序使用，以帮助解决每个域的浏览器并行请求限制；子域值在选项中指定;默认为 a, b 或 c , 可以省略), {z} — 缩放级别, {x} 和 {y} — 瓦片坐标。 {r} 可以用来在URL中添加 "@2x" 以加载视网膜瓦片
            //let gaoDeLayer = L.tileLayer(window.mapUrl + "/mapservice/MapImageServer?Z={z}&C={x}&R={y}&Layer=shanxisl&type=normal", {});
            let gaoDeLayer = L.tileLayer(this.Url, { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' });
            gaoDeLayer.addTo(this.map);
            // 定义控件
            L.EditControl = L.Control.extend({
                // 定义控件的参数
                options: {
                    position: "topleft", // 地图的左上角
                    callback: null,
                    kind: "",
                    html: ""
                },
                // 添加控件的内容（框选控件）
                onAdd(map) {
                    let container = L.DomUtil.create("div", "leaflet-control leaflet-bar");
                    let link = L.DomUtil.create("a", "", container);
                    link.href = "#";
                    link.title = "框选";
                    link.innerHTML = this.options.html;
                    L.DomEvent.on(link, "click", L.DomEvent.stop).on(
                        link,
                        "click",
                        function () {
                            window.LAYER = this.options.callback.call(map.editTools);
                        },
                        this
                    );
                    return container;
                }
            });
            // 删除控件
            L.DeleteControl = L.Control.extend({
                options: {
                    position: "topleft",
                    callback: null,
                    kind: "rectangle",
                    html: "<i class='el-icon-delete'>del</i>"
                },
                onAdd(map) {
                    // 创建一个class为'leaflet-control leaflet-bar'的div
                    let container = L.DomUtil.create("div", "leaflet-control leaflet-bar");
                    // 创建一个a标签悬停进行按钮提示
                    let link = L.DomUtil.create("a", "", container);
                    link.href = "#";
                    link.title = "清除";
                    // 设置显示的按钮图标
                    link.innerHTML = this.options.html;
                    // 处理dom点击事件（删除按钮的点击事件）
                    L.DomEvent.on(link, "click", L.DomEvent.stop).on(
                        link,
                        "click",
                        function () {
                            if (_this.$store.state.boxSelectionValue.length > 0) {
                                _this.editlayers.forEach(item => {
                                    map.removeLayer(item);
                                });
                                _this.editlayers = [];

                                _this.boxSelection = [];
                                _this.$emit("getboxSelection", _this.boxSelection);
                                _this.$store.commit("newboxSelectionValue", _this.boxSelection);
                                sessionStorage.removeItem("boxSelection");
                                _this.$emit("getLats", []);
                                sessionStorage.removeItem("baseList");
                            } else {
                                if (_this.editlayers.length > 0) {
                                    _this.editlayers.forEach(item => {
                                        sessionStorage.setItem("baseList", []);
                                        map.removeLayer(item);
                                    });
                                    _this.editlayers = [];
                                }
                                _this.boxSelection = [];
                                _this.$emit("getboxSelection", _this.boxSelection);
                                _this.$store.commit("newboxSelectionValue", _this.boxSelection);
                                sessionStorage.removeItem("boxSelection");
                                _this.$emit("getLats", []);
                                sessionStorage.removeItem("baseList");
                            }
                        },
                        this
                    );
                    return container;
                }
            });
            //  添加删除控件在地图上
            this.map.addControl(new L.DeleteControl());
            // 框选控件
            L.NewRectangleControl = L.EditControl.extend({
                options: {
                    position: "topleft",
                    callback: this.map.editTools.startRectangle,
                    kind: "rectangle",
                    html: "<i class='el-icon-edit'>edit</i>"
                }
            });
            //  添加编辑控件在地图上
            this.map.addControl(new L.NewRectangleControl());
            // ...................
            if (this.$route.path === "/oneClickQuery") {
                let boxselectList = JSON.parse(sessionStorage.getItem("boxSelection"));
                if (boxselectList && boxselectList.length > 0) {
                    var rec = L.rectangle(boxselectList).addTo(this.map);
                    rec.enableEdit();
                    this.editlayers.push(rec);
                }
            } else {
                if (this.$store.state.boxSelectionValue.length > 0) {
                    var rec = L.rectangle(this.$store.state.boxSelectionValue).addTo(this.map);
                    rec.enableEdit();
                    this.editlayers.push(rec);
                    // this.map.fitBounds(rec.getBounds())
                    // rec.on("dbclick", L.DomEvent.stop).on("dbclick", rec.toggleEdit);
                }
            }
            // ...................
            // var rec = L.rectangle([
            //   [43.1235, 1.255],
            //   [43.1235, 1.259],
            // ]).addTo(this.map);
            // rec.enableEdit();
            // rec.on("dbclick", L.DomEvent.stop).on("dbclick", rec.toggleEdit);
            // 绘图
            this.map.editTools.on("editable:drawing:end", e => {
                // let arr = [];
                // e.layer._latlngs[0].forEach((item) => {
                //   arr.push({ lat: item.lat, lon: item.lng });
                // });
                // e.layer._latlngs[0].forEach((item) => {
                //   item.__vertex.dragging.disable();
                // });
                this.editlayers.forEach(item => {
                    // 在地图上移除给定的图层
                    this.map.removeLayer(item);
                });
                // this.editlayers.push(e.layer);
                // this.getStations(e);
            });
            // 顶点拖动
            this.map.editTools.on("editable:vertex:dragend", e => {
                // this.editlayers.forEach((item) => {
                //   this.map.removeLayer(item);
                // });

                this.editlayers.push(e.layer);
                this.getStations(e);
            });
        },
        // 定位
        dingwei(val) {
            if (val[0].lat !== "" && val[0].lat !== null && val[0].lon !== "" && val[0].lon !== null) {
                this.map.eachLayer(layer => {
                    if (layer.options.icon) {
                        if (layer.options.icon.options.iconUrl === this.NewUrl) {
                            layer.setIcon(
                                L.icon({
                                    iconUrl: this.icons,
                                    iconSize: [20, 20]
                                })
                            );
                        }
                        let pos = layer.getLatLng();
                        if (pos.lat == val[0].lat && pos.lng == val[0].lon) {
                            layer.setIcon(
                                L.icon({
                                    iconUrl: this.NewUrl,
                                    iconSize: [30, 30]
                                })
                            );
                        }
                    }
                    this.map.panTo([val[0].lat, val[0].lon], {
                        animate: true
                    });
                });
            } else {
                this.$message("该数据没有基站信息");
            }
        },
        // 提取经纬度
        getLats(val) {
            let arr = [];
            val.layer._latlngs[0].forEach(item => {
                arr.push({ lat: item.lat, lon: item.lng });
            });
            return arr;
        },
        getposition(val) {
            this.map.panTo([val.lat, val.lon], {
                animate: true
            });
        },
        async getStations(val) {
            this.boxSelection = this.getLats(val);
            this.$emit("getboxSelection", this.boxSelection);

            let latList = this.getLats(val);
            // const { data: res } = await getBaseStations({
            //     query_data: JSON.stringify(latList)
            // });
            // if (res.statusCode === "0") {
            //     if (res.data.list.length === 0) {
            //         this.$message.error("框选区域无基站，请重新框选");
            //         this.map.removeLayer(val.layer);
            //     } else if (res.data.list.length > 100) {
            //         this.$message.error("框选区域包含基站过多，请重新框选");
            //         this.map.removeLayer(val.layer);
            //     } else {
            //         let baseList = [];
            //         res.data.list.forEach(item => {
            //             baseList.push({ tac: item.lac, uli: item.ci });
            //         });
            //         this.$emit("getLats", baseList);
            //     }
            // }
        },
        // 清除框选
        clear() {
            if (this.editlayers.length > 0) {
                this.editlayers.forEach(item => {
                    this.map.removeLayer(item);
                });
                this.editlayers = [];
            }
        }
    }
};
</script>

<style>
.map {
    width: 100%;
    /* height: 100%; */
    height: calc(100vh - 400px);
}

.toolclick {
    background: rgba(0, 0, 0, 0.7);
    color: #fff;
    border-color: rgba(0, 0, 0, 0.1);
    padding: 10px 18px;
    z-index: 99;
    font-size: 14px;
}

.TooltipAdress {
    display: flex;
}

.location {
    width: 150px;
    word-wrap: break-word;
    word-break: break-all;
    white-space: pre-wrap;
}

.contentHighlight {
    /* padding: 5px; */
    /* background: pink; */
    /* margin-top: 5px; */
    width: 25px !important;
    height: 25px !important;
    /* border: 1px solid red; */
    border-radius: 50%;
    margin-left: -18px !important;
    margin-top: -27px !important;
    /* -webkit-animation-name: "ripple";
  -webkit-animation-duration: 2s;
  -webkit-animation-timing-function: ease;
  -webkit-animation-delay: 0s;
  -webkit-animation-iteration-count: infinite;
  -webkit-animation-direction: alternate; */
}
</style>
